from openerp import rpc
import cherrypy
import datetime
import pytz
DATE_FORMAT_GMT = '%a, %d %b %Y %H:%M:%S GMT'
DATE_FORMAT_ISO = '%Y-%m-%d %H:%M:%S'
MODULE_NAME = 'check_user_online'
 
def _get_user_id():
    return rpc.session.storage['uid']
 
def _get_user_details():
    return rpc.RPCProxy('res.users').read(_get_user_id())
 
def update_user_session(data):
    rpc.RPCProxy('kdvn.sql.execute').execute("Update res_users set expiration_date=to_timestamp(case when '%s'='None' then null else '%s' end, 'YYYY-mm-dd HH24:MI:SS'),session_id=case when '%s'='None' then null else '%s' end where id=%s" %(data['expiration_date'],data['expiration_date'],data['session_id'],data['session_id'],_get_user_id()))
    #write(_get_user_id(), data, rpc.session.context)
 
def is_check_user_online_module_installed():
#    check_user_online_module_ids = rpc.RPCProxy('ir.module.module').search([('name', '=', MODULE_NAME), ('state', '=', 'installed')])
#    if len(check_user_online_module_ids)<=0:
#        return None
    if not rpc.session.storage.get(MODULE_NAME):
        check_user_online_module_ids = rpc.RPCProxy('ir.module.module').search([('name', '=', MODULE_NAME), ('state', '=', 'installed')])
        user_details = _get_user_details()
        rpc.session.storage[MODULE_NAME] = ((len(check_user_online_module_ids) == 1) and ('session_id' in user_details.keys()))
    return rpc.session.storage[MODULE_NAME]
 
def _get_user(): 
    return rpc.session.storage['user'] 
 
def _get_date_string(date_obj, date_format): 
    date_string = None 
    if date_obj: 
        date_string = date_obj.strftime(date_format)
    return date_string
 
def _get_date_obj(date_string, date_format):
    date_obj = None
    if date_string:
        date_obj = datetime.datetime.strptime(date_string, date_format)
    return date_obj
 
def get_date_obj(date_string):
    return _get_date_obj(date_string, DATE_FORMAT_GMT)
 
def _get_local_time_in_gmt():
    current_gmt_date = datetime.datetime.now(pytz.timezone('GMT'))
    current_gmt_date_string = _get_date_string(current_gmt_date, DATE_FORMAT_GMT)# -_get_date_obj('0, 0 0 0 0:59:0 GMT', DATE_FORMAT_GMT)
    current_date = _get_date_obj(current_gmt_date_string, DATE_FORMAT_GMT)
    return current_date

def update_users_status(): #has_user_loged_in
    if is_check_user_online_module_installed():
        current_date = _get_local_time_in_gmt()
        rpc.RPCProxy('kdvn.sql.execute').execute("Update res_users set is_online=True where expiration_date >= to_timestamp('%s', 'YYYY-mm-dd HH24:MI:SS')" %(current_date))     
        rpc.RPCProxy('kdvn.sql.execute').execute("Update res_users set is_online=False where (expiration_date is null or session_id is null) or expiration_date < to_timestamp('%s', 'YYYY-mm-dd HH24:MI:SS')" %(current_date))
    return True

 
def has_user_logged_in(action): #has_user_loged_in
    restrict_login = False
    if action == 'login' and is_check_user_online_module_installed():
        result = _get_user_details()
        previous_expiration_date_string = result['expiration_date']
        previous_expiration_date = _get_date_obj(previous_expiration_date_string, DATE_FORMAT_ISO) 
 
        cookie = cherrypy.response.cookie
        current_session_id = cookie['session_id'].value
        current_expiration_date = _get_date_obj(cookie['session_id']['expires'], DATE_FORMAT_GMT) 
        current_date = _get_local_time_in_gmt()
 
        if previous_expiration_date and (previous_expiration_date - current_date > datetime.timedelta(0)):
            # Multiple Login.
            restrict_login = True
        else:
            # Write Current Expiration Date to database. Login success. 
            data = {'session_id' : current_session_id, 'expiration_date' : str(current_expiration_date)} 
            update_user_session(data)
    return restrict_login
 
def clear_session():
    if is_check_user_online_module_installed():
        result = _get_user_details()
        cookie = cherrypy.response.cookie
        current_session_id = cookie['session_id'].value
        if result['session_id'] and result['session_id'] == current_session_id:
            data = {'session_id' : None, 'expiration_date' : None,'is_online':False}
            update_user_session(data)